package com.zanglikun.rocketmq.batch;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zanglikun
 * @Date: 2022/3/31 20:41
 * @Description: 批量发送消息，注意单次消息最大不得超过该4Mb。
 */
public class BatchProducer {
    public static void main(String[] args) throws Exception {
        // todo 1 创建消息生产者对象,同时指定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        // todo 2 指定NameServer地址
        producer.setNamesrvAddr("192.168.253.128:9876;192.168.253.129:9876");
        // todo 3 启动生产者
        producer.start();

        List<Message> messages = new ArrayList();
        // todo 4 创建消息对象,同时指定topic、tags、body
        for (int i = 0; i < 10; i++) {
            Message message = new Message("Batch", "Tag1", ("你好" + i).getBytes());
            messages.add(message);
        }

        // todo 5 发送消息
        SendResult sendResult = producer.send(messages);
        // todo 6 处理发送结果
        SendStatus sendStatus = sendResult.getSendStatus();
        String msgId = sendResult.getMsgId();
        int queueId = sendResult.getMessageQueue().getQueueId();
        System.out.println("消息发送状态" + sendStatus + ",消息Id:" + msgId + ",消息队列Id" + queueId);

        // todo 7 关闭生产者
        producer.shutdown();
    }
}
